package com.edu.whty.task.sync;

import com.alibaba.fastjson.JSONObject;
import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.HttpClient;
import com.edu.whty.common.tools.OpenUtil;
import com.edu.whty.common.tools.kafka.CommonMessage;
import com.edu.whty.common.tools.redis.RedisUtil;
import com.edu.whty.entity.base.JobMonitor;
import com.edu.whty.entity.cloud.UserResRequest2;
import com.edu.whty.service.CourseService;
import com.edu.whty.service.JobMonitorService;
import com.edu.whty.service.UserTextBookService;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 上行同步任务
 */
@Component
@Transactional
public class UpSyncDataTask {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserTextBookService userTextBookService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private JobMonitorService jobMonitorService;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${rrtbk.url}")
    private String rrtbkUrl;

    @Value("${rrtbk.api.upSync}")
    private String upSync;

    @Value("${rrtbk.isCloud}")
    private boolean isCloud;

    @Async
    @Scheduled(cron = "0 0/5 * * * ?")  //每30分钟执行一次
    public void upSyncData() {
        if (!isCloud) {
            logger.info("starting up sync data task");

            try {
                String upSyncUrl = rrtbkUrl + upSync+"?accessToken=" + OpenUtil.createTokenByUrl(rrtbkUrl);
                //同步教材
                List<Map<String, Object>> upSyncUserTextBookList = userTextBookService.getUpSyncUserTextBook();
                if (upSyncUserTextBookList.size() > 0) {
                    CommonMessage upSyncUserTextBookMessage = new CommonMessage();
                    upSyncUserTextBookMessage.setData(upSyncUserTextBookList);
                    upSyncUserTextBookMessage.setTable("tb_user_textbook");
                    logger.info("上行同步教材url:" + upSyncUrl + ";请求参数:" + JSONObject.toJSONString(upSyncUserTextBookMessage));
                    String textbookResponse = HttpClient.doJSONPostMethod(upSyncUrl, JSONObject.toJSONString(upSyncUserTextBookMessage));
                    JSONObject textbookResponseObject = JSONObject.parseObject(textbookResponse);
                    if(textbookResponseObject.getString("resCode").equals("000000")){
                        userTextBookService.finishUpSyncUserTextBook();
                    } else {
                        logger.error("up sync tb_user_textbook failed: " + textbookResponseObject.getString("resMsg"));
                    }
                }

                //同步课程资源
                List<Map<String, Object>> upSyncCourseResList = courseService.getUpSyncCourseRes();
                if (upSyncCourseResList.size() > 0) {
                    CommonMessage upSyncCourseResMessage = new CommonMessage();
                    upSyncCourseResMessage.setData(upSyncCourseResList);
                    upSyncCourseResMessage.setTable("tb_course_res");
                    logger.info("上行同步课程资源url:" + upSyncUrl + ";请求参数:" + JSONObject.toJSONString(upSyncCourseResMessage));
                    String courseResResponse = HttpClient.doJSONPostMethod(upSyncUrl, JSONObject.toJSONString(upSyncCourseResMessage));
                    JSONObject courseResResponseObject = JSONObject.parseObject(courseResResponse);
                    if(courseResResponseObject.getString("resCode").equals("000000")){
                        courseService.finishUpSyncCourseRes();
                    } else {
                        logger.error("up sync tb_course_res failed: " + courseResResponseObject.getString("resMsg"));
                    }
                }

                //同步用户课程
                List<Map<String, Object>> upSyncCourseUserList = courseService.getUpSyncCourseUser();
                if (upSyncCourseUserList.size() > 0) {
                    CommonMessage upSyncCourseUserMessage = new CommonMessage();
                    upSyncCourseUserMessage.setData(upSyncCourseUserList);
                    upSyncCourseUserMessage.setTable("tb_course_user");
                    logger.info("上行同步用户课程url:" + upSyncUrl + ";请求参数:" + JSONObject.toJSONString(upSyncCourseUserMessage));
                    String courseUserResponse = HttpClient.doJSONPostMethod(upSyncUrl, JSONObject.toJSONString(upSyncCourseUserMessage));
                    JSONObject courseUserResponseObject = JSONObject.parseObject(courseUserResponse);
                    if(courseUserResponseObject.getString("resCode").equals("000000")){
                        courseService.finishUpSyncCourseUser();
                    } else {
                        logger.error("up sync tb_course_user failed: " + courseUserResponseObject.getString("resMsg"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("up sync data task failed:" + e.getMessage());
            }

            logger.info("ending up sync data task");
        }
    }

    @Scheduled(cron = "5 */5 * * * ?")  //每15分钟执行一次
    public void synJxzsData(){
        if (isCloud) {

            PageHelper.startPage(1, 1);
            JobMonitor jobMonitor = new JobMonitor();
            jobMonitor.setStatus("0");
            List<JobMonitor> jobMonitorList = jobMonitorService.queryJxzsJobMonitorList(jobMonitor);
            if(jobMonitorList==null || jobMonitorList.size()<=0){
                return;
            }
            JobMonitor job = jobMonitorList.get(0);
            String syncFlag = null;
            boolean hasKey = redisUtil.hasKey("sync_jxzs_job"+job.getUserIds());
            logger.info("任务sync_jxzs_job"+job.getUserIds()+"是否存在："+hasKey);
            if (hasKey) {
                syncFlag = (String) redisUtil.get("sync_jxzs_job"+job.getUserIds());
            }
            if (StringUtils.isNotEmpty(syncFlag) && "1".equals(syncFlag)) {
                logger.info("已有进程执行,不进行同步");
                return;
            }
            try {
                redisUtil.set("sync_jxzs_job"+job.getUserIds(),"1",7200);
                logger.info("任务sync_jxzs_job"+job.getUserIds()+"是否存在："+redisUtil.hasKey("sync_jxzs_job"+job.getUserIds()));
                JSONObject obj = new JSONObject();
                obj.put("userSessionId","synCloudList");
                obj.put("platformCode",job.getPlatformCode());
                obj.put("loginPlatformCode",job.getPlatformCode());
                obj.put("userId",job.getUserIds());
                JSONObject pageObj = new JSONObject();
                pageObj.put("currPage",1);
                pageObj.put("pageSize",10);
                obj.put("pageInfo",pageObj);
                logger.info("当前同步的用户userId为:"+job.getUserIds());
                String  upSyncUrl = "https://kcapi-p.huijiaoyun.com/res-course/synData/synCloudList";
                String textbookResponse = HttpClient.doJSONPostMethod(upSyncUrl, com.alibaba.fastjson.JSONObject.toJSONString(obj));
                net.sf.json.JSONObject result = net.sf.json.JSONObject.fromObject(textbookResponse);
                String resultCode = result.getString("result");
                if (Constant.SUCCESS_CODE.equals(resultCode)) {
                    net.sf.json.JSONObject data = result.optJSONObject("data");
                    net.sf.json.JSONArray array = data.optJSONArray("list");
                    List<UserResRequest2> userReslist = baseJson(array);
                    for(UserResRequest2 userRes:userReslist){
                        userRes.setSourceFrom("4");
                    }
                    courseService.saveCloudRes(userReslist, "2","cloud");
                    net.sf.json.JSONObject page = data.optJSONObject("pageInfo");
                    Integer totalPage = page.optInt("totalPage");
                    for(int i=2; i<=totalPage;i++){
                        pageObj.put("currPage",i);
                        obj.put("pageInfo",pageObj);
                        textbookResponse = HttpClient.doJSONPostMethod(upSyncUrl, com.alibaba.fastjson.JSONObject.toJSONString(obj));
                        result = net.sf.json.JSONObject.fromObject(textbookResponse);
                        resultCode = result.getString("result");
                        if (Constant.SUCCESS_CODE.equals(resultCode)) {
                            data = result.getJSONObject("data");
                            array = data.getJSONArray("list");
                            userReslist = baseJson(array);
                            for(UserResRequest2 userRes:userReslist){
                                userRes.setSourceFrom("4");
                            }
                            courseService.saveCloudRes(userReslist, "2", "cloud");
                        }
                    }

                    job.setStatus("1");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateStr= sdf.format(new Date());
                    job.setSynTime(dateStr);
                    jobMonitorService.updateJxzsJobMonitor(job);
                    redisUtil.del("sync_jxzs_job"+job.getUserIds());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    public List<UserResRequest2> baseJson(net.sf.json.JSONArray array){
        List<UserResRequest2> list = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            UserResRequest2 userResRequest2 = new UserResRequest2();
            userResRequest2.setClassfiitonTypeId(array.getJSONObject(i).optString("classfiitonId"));
            userResRequest2.setUserId(array.getJSONObject(i).optString("creatorId"));
            userResRequest2.setUserName(array.getJSONObject(i).optString("creatorName"));
            userResRequest2.setFId(array.getJSONObject(i).optString("fid"));
            userResRequest2.setFileLength(array.getJSONObject(i).optString("fileLength"));
            userResRequest2.setFileExt(array.getJSONObject(i).optString("fileExt"));
            userResRequest2.setFileSize(array.getJSONObject(i).optString("fileSize"));
            userResRequest2.setMd5(array.getJSONObject(i).optString("md5"));
            userResRequest2.setUserId(array.getJSONObject(i).optString("creatorId"));
            userResRequest2.setDownloadUrl(array.getJSONObject(i).optString("downUrl"));
            userResRequest2.setPreviewUrl(array.getJSONObject(i).optString("previewUrl"));
            userResRequest2.setTitle(array.getJSONObject(i).optString("title"));
            userResRequest2.setPeriodId(array.getJSONObject(i).optString("coursePeriodId"));
            userResRequest2.setPeriodName(array.getJSONObject(i).optString("coursePeriodName"));
            userResRequest2.setSubjectId(array.getJSONObject(i).optString("courseSubjectId"));
            userResRequest2.setSubjectName(array.getJSONObject(i).optString("courseSubjectName"));
            userResRequest2.setEditionId(array.getJSONObject(i).optString("courseEditionId"));
            userResRequest2.setEditionName(array.getJSONObject(i).optString("courseEditionName"));
            userResRequest2.setVolumeId(array.getJSONObject(i).optString("courseVolumeId"));
            userResRequest2.setVolumeName(array.getJSONObject(i).optString("courseVolumeName"));
            userResRequest2.setTextbookId(array.getJSONObject(i).optString("courseTextbookId"));
            userResRequest2.setTextbookName(array.getJSONObject(i).optString("courseTextbookName"));
            userResRequest2.setChapterId(array.getJSONObject(i).optString("courseChapterid"));
            userResRequest2.setChapterName(array.getJSONObject(i).optString("courseChaptername"));
            userResRequest2.setOrgId("49eafc4bc4184a65a4bb9192e357fec8");
            userResRequest2.setLoginPlatformCode(array.getJSONObject(i).optString("loginPlatformCode"));

            list.add(userResRequest2);
        }
        return list;
    }
}
